package com.gexiaobao.pigeon.viewmodel

import android.view.View
import androidx.databinding.ObservableInt
import androidx.lifecycle.MutableLiveData
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.model.bean.BobInfoResponse
import com.gexiaobao.pigeon.app.model.bean.DeviceListBean
import com.gexiaobao.pigeon.app.model.bean.FeatherColorResponse
import com.gexiaobao.pigeon.app.model.bean.PigeonBean
import com.gexiaobao.pigeon.app.model.bean.PigeonFosterBean
import com.gexiaobao.pigeon.app.model.bean.PigeonRaceCharResponse
import com.gexiaobao.pigeon.app.model.bean.RingSnResponse
import com.gexiaobao.pigeon.app.model.bean.TrainingRecordResponse
import com.gexiaobao.pigeon.app.model.bean.UiState
import com.gexiaobao.pigeon.app.model.param.RingInfoParams
import com.gexiaobao.pigeon.app.model.param.RingSnParams
import com.gexiaobao.pigeon.app.network.ListDataUiState
import com.gexiaobao.pigeon.app.network.apiService
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.IntObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState
import java.io.File

/**
 * created by : hxw
 * @date : 20221128
 * Describe :
 */
class MyPigeonViewModel : BaseViewModel() {
    private var pageNo: Int = 1

    val searchName = StringObservableField()
    val pigeonNum = StringObservableField()
    val pigeonType = StringObservableField()
    val autoPigeon = BooleanObservableField()
    val fosterPigeon = BooleanObservableField()

    /** 添加赛鸽 */
    val pigeonMasterName = StringObservableField()
    val pigeonNickName = StringObservableField()
    val pigeonHouseName = StringObservableField()
    val pigeonRingId = StringObservableField()//足环号
    val pigeonRingSn = StringObservableField()//电子环号
    val pigeonFeatherColor = StringObservableField()//羽色
    val pigeonFeatherColorPosition = IntObservableField()//羽色下标
    val pigeonFather = StringObservableField()//父亲足环号
    val pigeonMother = StringObservableField()//母亲足环号
    val pigeonRaiser = StringObservableField()//育种者
    val pigeonBirthday = StringObservableField()//出壳日期
    val pigeonDesc = StringObservableField()//赛鸽介绍
    val pigeonSex = StringObservableField()//赛鸽性别
    val pigeonEyePattern = StringObservableField()//赛鸽眼沙

    //删除赛鸽
    val deletePigeon: MutableLiveData<UiState> = MutableLiveData()

    //删除全部赛鸽
    val deleteAllPigeon: MutableLiveData<UiState> = MutableLiveData()

    //添加和修改赛鸽
    val createPigeon: MutableLiveData<UiState> = MutableLiveData()

    //赛鸽列表信息
    var pigeonData: MutableLiveData<ListDataUiState<PigeonBean.RingInfo>> = MutableLiveData()

    /** 获取赛鸽详情 */
    var pigeonInfoResult: MutableLiveData<PigeonBean.RingInfo> = MutableLiveData()

    //寄养赛鸽列表信息
    var fosterPigeonData: MutableLiveData<ListDataUiState<PigeonFosterBean.ListData>> = MutableLiveData()

    //训放记录
    var trainingRecordResult: MutableLiveData<ListDataUiState<TrainingRecordResponse.InfoList>> = MutableLiveData()

    //公棚列表
    var BobInfoResult: MutableLiveData<BobInfoResponse> = MutableLiveData()

    //电子环号
    var ringSn = MutableLiveData<ResultState<RingSnResponse>>()

    //全部删除按钮是否显示
    var deleteVisible = object : ObservableInt(pigeonType) {
        override fun get(): Int {
            return if (pigeonType.get() == "1") {
                View.VISIBLE
            } else {
                View.GONE
            }
        }
    }

    //底部删除和修改按钮是否显示
    var llBottomVisible = object : ObservableInt(pigeonType) {
        override fun get(): Int {
            return if (pigeonType.get() == "1") {
                View.VISIBLE
            } else {
                View.GONE
            }
        }
    }

    //自养显示
    var autoVisible = object : ObservableInt(autoPigeon) {
        override fun get(): Int {
            return if (autoPigeon.get()) {
                View.VISIBLE
            } else {
                View.GONE
            }
        }
    }

    //寄养显示
    var fosterVisible = object : ObservableInt(fosterPigeon) {
        override fun get(): Int {
            return if (fosterPigeon.get()) {
                View.VISIBLE
            } else {
                View.GONE
            }
        }
    }

    fun geyRingSn(body: RingSnParams) {
        request({ apiService.getRing(body) }, ringSn)
    }

    //设备列表
    var deviceList: MutableLiveData<DeviceListBean> = MutableLiveData()
    fun getDeviceList() {
        request({ apiService.getDevice() }, {
//            val listDataUiState = ListDataUiState(
//                isSuccess = true, isEmpty = it.isEmpty(), listData = it.list
//            )
            deviceList.value = it
        }, {
//            val listDataUiState = ListDataUiState(isSuccess = false, errMessage = it.msg, listData = arrayListOf<DeviceListBean.DataList>())
//            deviceList.value = listDataUiState
            RxToast.showToast(it.msg)
        })
    }

    fun getPigeonList(isRefresh: Boolean, type: String, ringId: String) {
        if (isRefresh) {
            pageNo = 1
        }
        val body = hashMapOf<String, Any>().apply {
            put("type", type)
            put("ps", 20)
            put("pn", pageNo)
            put("ringId", ringId)
        }
        request({ apiService.getPigeonList(body) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                total = it.total,
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.ringInfo
            )
            pigeonData.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(
                isSuccess = false, errMessage = it.msg, errCode = it.code, isRefresh = isRefresh, listData = arrayListOf<PigeonBean.RingInfo>()
            )
            pigeonData.value = listDataUiState
        })
    }

    /** 获取赛鸽寄养列表 */
    fun getLoftOrgListByUserWithOrg(isRefresh: Boolean, mOrgId: String, raceId: String, ringOrMember: String) {
        if (isRefresh) {
            pageNo = 1
        }
        request({ apiService.getLoftOrgListByUserWithOrg(pageNo, 20, mOrgId, raceId, ringOrMember) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                hasMore = it.hasMore(),
                listData = it.list,
                total = it.total
            )
            fosterPigeonData.value = listDataUiState
        }, {
            val listDataUiState =
                ListDataUiState(isSuccess = false, isRefresh = isRefresh, errMessage = it.msg, listData = arrayListOf<PigeonFosterBean.ListData>())
            fosterPigeonData.value = listDataUiState
        })
    }

    fun getPigeonTraining(isRefresh: Boolean, pigeonId: String) {
        if (isRefresh) {
            pageNo = 1
        }

        request({ apiService.getPigeonTraining(pigeonId, pageNo, 20) }, {
            pageNo++
            val listDataUiState = ListDataUiState(
                isSuccess = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                total = it.total,
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.list
            )
            trainingRecordResult.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(
                isSuccess = false,
                errMessage = it.msg,
                errCode = it.code,
                isRefresh = isRefresh,
                listData = arrayListOf<TrainingRecordResponse.InfoList>()
            )
            trainingRecordResult.value = listDataUiState
        })
    }

    /** 删除赛鸽 */
    fun deletePigeon(id: String) {
        request({ apiService.deletePigeon(id) }, {
            val deleteState = UiState(isSuccess = true)
            deletePigeon.value = deleteState
        }, {
            val deleteState = UiState(isSuccess = false, errorMsg = it.msg)
            deletePigeon.value = deleteState
        })
    }

    /** 删除全部赛鸽 */
    fun deletePigeonList() {
        request({ apiService.deletePigeonList() }, {
            val deleteState = UiState(isSuccess = true)
            deleteAllPigeon.value = deleteState
        }, {
            val deleteState = UiState(isSuccess = false, errorMsg = it.msg)
            deleteAllPigeon.value = deleteState
        })
    }

    /** 获取羽色列表 */
    var featherColor: MutableLiveData<ListDataUiState<FeatherColorResponse.ColorList>> = MutableLiveData()
    fun getFeatherColor() {
        request({ apiService.getFeatherColor() }, {
            val listDataUiState = ListDataUiState(
                isSuccess = true, isEmpty = it.isEmpty(), listData = it.list
            )
            featherColor.value = listDataUiState
        }, {
            val listDataUiState = ListDataUiState(isSuccess = false, errMessage = it.msg, listData = arrayListOf<FeatherColorResponse.ColorList>())
            featherColor.value = listDataUiState
        })
    }

    /** 获取用户所属公棚列表 */
    fun getLoftOrgListByUser() {
        request({ apiService.getLoftOrgListByUser(1, 999999) }, {
            BobInfoResult.value = it
        }, {
            RxToast.showToast(it.msg)
        })
    }

    /** 获取赛鸽详情 */
    fun getPigeonInfo(pigeonId: Int) {
        request({ apiService.getPigeonInfo(pigeonId) }, {
            pigeonInfoResult.value = it
        }, {
            RxToast.showToast(it.msg)
        })
    }

    fun createPigeon(bean: RingInfoParams) {
        val imgFileBody = bean.bodyPic
        val imgFileFly = bean.featherPic
        val imgFileLeft = bean.leftHead
        val imgFileRight = bean.rightHeadPic
        if (imgFileBody == null && imgFileFly == null && imgFileLeft == null && imgFileRight == null) {
            request({ apiService.createPigeon(bean) }, {
                val createResult = UiState(isSuccess = true)
                createPigeon.value = createResult
                //请求成功 已自动处理了 请求结果是否正常
                eventViewModel.toRefreshList.value = true
            }, {
                //请求失败 网络异常，或者请求结果码错误都会回调在这里
                val createResult = it.errorLog?.let { it1 -> UiState(isSuccess = false, errorMsg = it1) }
                createPigeon.value = createResult
            })
            return
        }

        val fileList = HashMap<String, File?>()
        val hashMap = HashMap<String, String>()
        hashMap["fosterName"] = bean.fosterName
        hashMap["ringId"] = bean.ringId
        hashMap["ringSn"] = bean.ringSn
        hashMap["sex"] = bean.sex.toString()
        hashMap["featherColor"] = bean.featherColor.toString()
        hashMap["eyePattern"] = bean.eyePattern.toString()
        hashMap["fatherRingId"] = bean.fatherRingId
        hashMap["motherRingId"] = bean.motherRingId
        hashMap["raiser"] = bean.raiser
        hashMap["birthday"] = bean.birthday
        hashMap["pigeonDesc"] = bean.pigeonDesc

        if (imgFileBody != null) {
            fileList["bodyPic"] = imgFileBody
        } else {
            hashMap["bodyPic"] = ""
        }
        if (imgFileFly != null) {
            fileList["featherPic"] = imgFileFly
        } else {
            hashMap["featherPic"] = ""
        }
        if (imgFileLeft != null) {
            fileList["leftHead"] = imgFileLeft
        } else {
            hashMap["leftHead"] = ""
        }
        if (imgFileRight != null) {
            fileList["rightHeadPic"] = imgFileRight
        } else {
            hashMap["rightHeadPic"] = ""
        }
        val body = SettingUtil.filesToMultipartBody(fileList, hashMap)
        request({ apiService.createPigeon(body) }, {
            val createResult = UiState(isSuccess = true)
            createPigeon.value = createResult
            eventViewModel.toRefreshList.value = true
        }, {
            val createResult = it.errorLog?.let { it1 -> UiState(isSuccess = false, errorMsg = it1) }
            createPigeon.value = createResult
        })
    }

    //修改赛鸽（附带图片）
    val modifyPigeonPicResult: MutableLiveData<UiState> = MutableLiveData()
    fun upDatePigeon(bean: RingInfoParams) {
        val imgFileBody = bean.bodyPic
        val imgFileFly = bean.featherPic
        val imgFileLeft = bean.leftHead
        val imgFileRight = bean.rightHeadPic
        if (imgFileBody == null && imgFileFly == null && imgFileLeft == null && imgFileRight == null) {
            request({ apiService.updatePigeon(bean) }, {
                val updateResult = UiState(isSuccess = true)
                createPigeon.value = updateResult
                //请求成功 已自动处理了 请求结果是否正常
                eventViewModel.toRefreshList.value = true
//                activity.finish()
            }, {
                //请求失败 网络异常，或者请求结果码错误都会回调在这里
                val createResult = it.errorLog?.let { it1 -> UiState(isSuccess = false, errorMsg = it1) }
                createPigeon.value = createResult
            })
            return
        }

        val fileList = HashMap<String, File?>()
        val hashMap = HashMap<String, String>()
        hashMap["id"] = bean.id.toString()
        hashMap["fosterName"] = bean.fosterName
        hashMap["ringId"] = bean.ringId
        hashMap["ringSn"] = bean.ringSn
        hashMap["sex"] = bean.sex.toString()
        hashMap["featherColor"] = bean.featherColor.toString()
        hashMap["eyePattern"] = bean.eyePattern.toString()

        if (imgFileBody != null) {
            fileList["bodyPic"] = imgFileBody
        } else {
            hashMap["bodyPic"] = ""
        }
        if (imgFileFly != null) {
            fileList["featherPic"] = imgFileFly
        } else {
            hashMap["featherPic"] = ""
        }
        if (imgFileLeft != null) {
            fileList["leftHead"] = imgFileLeft
        } else {
            hashMap["leftHead"] = ""
        }
        if (imgFileRight != null) {
            fileList["rightHeadPic"] = imgFileRight
        } else {
            hashMap["rightHeadPic"] = ""
        }
        val body = SettingUtil.filesToMultipartBody(fileList, hashMap)
        request({ apiService.updatePigeon(body) }, {
            //请求成功 已自动处理了 请求结果是否正常
//            eventViewModel.toRefreshList.value = true
            val deleteState = UiState(isSuccess = true)
            modifyPigeonPicResult.value = deleteState
        }, {
            val deleteState = UiState(isSuccess = false, errorMsg = it.msg)
            modifyPigeonPicResult.value = deleteState
        })
    }

    /** 获取赛鸽折线图 */
    val pigeonForceResult: MutableLiveData<PigeonRaceCharResponse> = MutableLiveData()
    fun getPigeonRaceChart(pigeonId: Int, raceId: Int, raceType: Int) {
        request({ apiService.getPigeonRaceChart(pigeonId, raceId, raceType) }, {
            pigeonForceResult.value = it
        }, {
            RxToast.showToast(it.msg)
        })
    }

}